package com.xy.netty.dome.echo.original;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * @author 1
 */
@Slf4j
public class TimeServerHandler implements  Runnable {

    private final Socket socket;

    public  TimeServerHandler(Socket socket){
        this.socket = socket;
    }


    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter  out = null;
        try {
            in = new BufferedReader( new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(),true);
            String body = null;
            while (( body = in.readLine())!= null && body.length()!=0){
                log.info("the time server receive msg :"+body);
                out.println(new Date().toString());
            }
        } catch (Exception e){
            log.error("读出或输入错误",e);
        } finally {
            if(in != null){
                try {
                    in.close();
                }catch (Exception e){
                    log.error("关闭输入流错误",e);
                }
            }
            if(out != null){
                try {
                    out.close();
                }catch (Exception e){
                    log.error("关闭输出流错误",e);
                }
            }
            if(this.socket != null){
                try{
                    this.socket.close();
                }catch (Exception e){
                    log.error("关闭socket错误",e);
                }
            }
            if(BioServer.getCurrentSocket().get()!=null){
                BioServer.getCurrentSocket().remove();
            }
        }

    }

}
